import 'dart:convert';
import 'dart:ffi';

import 'package:fluent_ui/fluent_ui.dart' as prefix;
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:http/http.dart' as http;
import '../tool/confirmButton.dart';
import '../tool/inputbox.dart';
import '../tool/radio.dart';

class Register extends StatefulWidget {
  const Register({super.key});

  @override
  State<StatefulWidget> createState() => _Register();
}

class _Register extends State<Register> {
  var account = "";
  var name = "";
  var password = "";
  var alliance = "";
  String examine = "";
  List<dynamic> group = [];
  void setAction(String value) {
    account = value;
  }

  void setName(value) {
    name = value;
  }

  void setPassword(value) {
    password = value;
  }

  void uploadButton() async {
    if (account == "" || name == "" || password == "") {
      Fluttertoast.showToast(msg: '不能为空');
      return;
    }
    final url = Uri.parse('http://127.0.0.1:5000/reg_examine');
    final headers = {'Content-Type': 'application/json;charset=utf-8'};
    final body = jsonEncode({'alliance': alliance});

    final request = http.Request('get', url);
    request.headers.addAll(headers);
    request.body = body;
    request.send().then((value) {
      http.Response.fromStream(value).then((response) {
        examine = jsonDecode(response.body)["msg"];
        registerAccount(examine);
      });
    }).catchError((value) {
      Fluttertoast.showToast(msg: '注册失败');
    });
  }

  void registerAccount(var check) async {
    final url = Uri.parse('http://127.0.0.1:5000/register');
    final headers = {'Content-Type': 'application/json;charset=utf-8'};
    final body = jsonEncode({
      'account': account,
      'name': name,
      'password': password,
      'alliance': alliance,
      'examine': examine
    });
    try {
      final request = http.Request('get', url);
      request.headers.addAll(headers);
      request.body = body;
      final response = await request.send();
      final responseBody = await response.stream.bytesToString();
      var jsonData = jsonDecode(responseBody);
      if (response.statusCode == 200 && jsonData["code"] == "200") {
        if (examine == "True") {
          Fluttertoast.showToast(msg: '请通知管理进行审核');
          Navigator.pop(context);
          setState(() {
            account = "";
            name = "";
            password = "";
          });
        } else {
          Fluttertoast.showToast(msg: '注册成功');
          Navigator.pop(context);
          setState(() {
            account = "";
            name = "";
            password = "";
          });
        }
      } else {
        Fluttertoast.showToast(msg: '注册失败');
      }
    } catch (e) {
      Fluttertoast.showToast(msg: '接口异常');
    }
  }

  @override
  void initState() {
    super.initState();
    final url = Uri.parse('http://127.0.0.1:5000/query_union');
    final headers = {'Content-Type': 'application/json;charset=utf-8'};
    final request = http.Request('get', url);
    request.headers.addAll(headers);
    request.send().then((value) {
      http.Response.fromStream(value).then((response) {
        setState(() {
          group = jsonDecode(response.body)["msg"];
          alliance = group[0];
        });
      });
    }).catchError((value) {
      Fluttertoast.showToast(msg: '初始化异常');
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('注册'),
        ),
        resizeToAvoidBottomInset: false,
        body: Container(
          height: double.infinity,
          width: double.infinity,
          padding: const EdgeInsets.only(left: 20, right: 20),
          decoration: const BoxDecoration(
            image: DecorationImage(
              image: AssetImage('image/register.jpeg'), // 设置背景图像
              fit: BoxFit.cover, // 图像自适应方式
            ),
          ),
          child: Center(
            widthFactor: 1,
            heightFactor: 1,
            child: Column(
              children: [
                Inputbox(
                  name: "用户名",
                  inputvalue: account,
                  setFunction: setAction,
                ),
                Inputbox(
                  name: "游戏名字",
                  setFunction: setName,
                  inputvalue: name,
                ),
                Inputbox(
                    name: "密码", setFunction: setPassword, inputvalue: password),
                const SizedBox(
                  height: 20,
                ),
                prefix.InfoLabel(
                  label: "联盟名",
                  labelStyle:
                      const TextStyle(fontSize: 24, color: Colors.white),
                  child: Container(
                      color: const prefix.Color.fromARGB(176, 255, 255, 255),
                      width: double.infinity,
                      child: singleChoice(
                        items: group != [] ? group : ["错误"],
                        selectedValue: alliance != "" ? alliance : "错误",
                      )),
                ),
                ConfirmButton(uploadButton: uploadButton)
              ],
            ),
          ),
        ));
  }
}
